using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

/// <summary>
/// UnityWebRequest 网络管理器
/// </summary>
public class NetMgr : MonoBehaviour
{
    public static NetMgr Instance;

    private void Awake()
    {
        Instance = this;
    }

    /// <summary>
    /// UnityWebRequest加载
    /// </summary>
    /// <param name="url">路径地址</param>
    /// <param name="audioType">Audio资源时加载类型</param>
    /// <param name="onFinishAction">加载完成后Action</param>
    /// <param name="downloadProgress">加载进度Action</param>
    /// <param name="downloadBytesAction">已加载字节Action</param>
    public void UnityWebRequestLoad<T>(string url, Action<T> onFinishAction = null,
        AudioType audioType = AudioType.MPEG,
        Action<float> downloadProgress = null, Action<ulong> downloadBytesAction = null) where T : class
    {
        StartCoroutine(UnityWebRequestLoadAsync<T>(url, onFinishAction, audioType, downloadProgress,
            downloadBytesAction));
    }

    // ReSharper disable Unity.PerformanceAnalysis
    /// <summary>
    /// UnityWebRequest加载异步
    /// </summary>
    /// <param name="url">路径地址</param>
    /// <param name="audioType">Audio资源时加载类型</param>
    /// <param name="onFinishAction">加载完成后Action</param>
    /// <param name="downloadProgress">加载进度Action</param>
    /// <param name="downloadBytesAction">已加载字节Action</param>
    /// <typeparam name="T">1.二进制：byte[] 2.图片：Texture 3.AB包：AssetBundle</typeparam>
    private IEnumerator UnityWebRequestLoadAsync<T>(string url, Action<T> onFinishAction,
        AudioType audioType = AudioType.MPEG,
        Action<float> downloadProgress = null, Action<ulong> downloadBytesAction = null) where T : class
    {
        UnityWebRequest req = UnityWebRequest.Get(url);
        if (typeof(T) == typeof(byte[]))
        {
            req.downloadHandler = new DownloadHandlerBuffer();
        }
        else if (typeof(T) == typeof(Texture))
        {
            req.downloadHandler = new DownloadHandlerTexture();
        }
        else if (typeof(T) == typeof(AssetBundle))
        {
            req.downloadHandler = new DownloadHandlerAssetBundle(req.url, 0);
        }
        else if (typeof(T) == typeof(AudioClip))
        {
            req.downloadHandler = new DownloadHandlerAudioClip(req.url, audioType);
        }
        else
        {
            Debug.LogWarning("未知类型：" + typeof(T));
            yield break;
        }

        req.SendWebRequest();
        while (!req.isDone)
        {
            downloadBytesAction?.Invoke(req.downloadedBytes);
            downloadProgress?.Invoke(req.downloadProgress);
            yield return null;
        }

        if (req.result == UnityWebRequest.Result.Success)
        {
            if (typeof(T) == typeof(byte[]))
            {
                onFinishAction?.Invoke(req.downloadHandler.data as T);
            }
            else if (typeof(T) == typeof(Texture))
            {
                onFinishAction?.Invoke(DownloadHandlerTexture.GetContent(req) as T);
            }
            else if (typeof(T) == typeof(AssetBundle))
            {
                onFinishAction?.Invoke(DownloadHandlerAssetBundle.GetContent(req) as T);
            }
            else if (typeof(T) == typeof(AudioClip))
            {
                onFinishAction?.Invoke(DownloadHandlerAudioClip.GetContent(req) as T);
            }
           
        }
        else
        {
            print(
                $"获取数据失败！ url:{url} req.result:{req.result} req.error:{req.error} req.responseCode:{req.responseCode}");
        }
    }
}